<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <input type="text" placeholder="Name" id="uname">
    <button type="button" id="btn1">设置Cookie</button>
    <button type="button" id="btn2">读取Cookie</button>
    <div id="cookieResult"></div>
    <script>
        //创建Cookie
        // document.cookie="username=Seagull";
        //读取Cookie
        // var x=document.cookie;
        //删除Cookie (同名字再设置一个空值)
        // document.cookie="username=";
        //示例：
        //存储
        // 设置Cookie按钮点击事件
        btn1.onclick = function() {
            var user = document.getElementById("uname").value;
            if (user) {
                setCookie("username", user);
                alert("Cookie设置成功");
            } else {
                alert("请输入姓名");
            }
        }

        // 读取Cookie按钮点击事件
        btn2.onclick = function() {
            var username = getCookie("username");
            if (username) {
                resultDiv.textContent = "读取到的Cookie值: " + username;
            } else {
                resultDiv.textContent = "未找到Cookie或已过期";
            }
        }

        // 设置Cookie函数，有效期设为10分钟
        function setCookie(cname, cvalue) {
            var now = new Date();
            now.setMinutes(now.getMinutes() + 10); // 有效期10分钟
            var expires = "expires=" + now.toUTCString();
            document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
        }

        // 读取Cookie函数
        function getCookie(cname) {
            var name = cname + "=";
            var decodedCookie = decodeURIComponent(document.cookie);
            var ca = decodedCookie.split(';');

            for (var i = 0; i < ca.length; i++) {
                var c = ca[i];
                while (c.charAt(0) == ' ') {
                    c = c.substring(1);
                }
                if (c.indexOf(name) == 0) {
                    return c.substring(name.length, c.length);
                }
            }
            return "";
        }
    </script>
</body>

</html>